<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设置名称" prop="settingName">
        <el-input
          v-model="queryParams.settingName"
          placeholder="请输入设置名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="启用状态" prop="isEnabled">
        <el-select v-model="queryParams.isEnabled" placeholder="请选择启用状态" clearable>
          <el-option label="启用" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['environment:notification:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['environment:notification:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['environment:notification:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['environment:notification:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-setting"
          size="mini"
          @click="handleMySettings"
        >我的设置</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="notificationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设置ID" align="center" prop="settingId" />
      <el-table-column label="用户ID" align="center" prop="userId" />
      <el-table-column label="设置名称" align="center" prop="settingName" />
      <el-table-column label="温度报警" align="center" prop="temperatureAlert">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.temperatureAlert == '1'" type="success">启用</el-tag>
          <el-tag v-else type="info">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="湿度报警" align="center" prop="humidityAlert">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.humidityAlert == '1'" type="success">启用</el-tag>
          <el-tag v-else type="info">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="空气质量报警" align="center" prop="airQualityAlert">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.airQualityAlert == '1'" type="success">启用</el-tag>
          <el-tag v-else type="info">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="启用状态" align="center" prop="isEnabled">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isEnabled == '1'" type="success">启用</el-tag>
          <el-tag v-else type="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['environment:notification:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['environment:notification:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleCheckAlert(scope.row)"
          >检测报警</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改通知设置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="设置名称" prop="settingName">
              <el-input v-model="form.settingName" placeholder="请输入设置名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用状态" prop="isEnabled">
              <el-switch
                v-model="form.isEnabled"
                active-value="1"
                inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">报警设置</el-divider>
        
        <el-row>
          <el-col :span="8">
            <el-form-item label="温度报警">
              <el-switch
                v-model="form.temperatureAlert"
                active-value="1"
                inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="湿度报警">
              <el-switch
                v-model="form.humidityAlert"
                active-value="1"
                inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="空气质量报警">
              <el-switch
                v-model="form.airQualityAlert"
                active-value="1"
                inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="气压报警">
              <el-switch
                v-model="form.pressureAlert"
                active-value="1"
                inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="光照报警">
              <el-switch
                v-model="form.lightAlert"
                active-value="1"
                inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="设备离线报警">
              <el-switch
                v-model="form.deviceOfflineAlert"
                active-value="1"
                inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">报警阈值设置</el-divider>

        <el-row v-if="form.temperatureAlert == '1'">
          <el-col :span="12">
            <el-form-item label="温度最低值" prop="temperatureMin">
              <el-input-number v-model="form.temperatureMin" :precision="1" :step="0.5" :min="-50" :max="100" />
              <span style="margin-left: 10px;">°C</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="温度最高值" prop="temperatureMax">
              <el-input-number v-model="form.temperatureMax" :precision="1" :step="0.5" :min="-50" :max="100" />
              <span style="margin-left: 10px;">°C</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="form.humidityAlert == '1'">
          <el-col :span="12">
            <el-form-item label="湿度最低值" prop="humidityMin">
              <el-input-number v-model="form.humidityMin" :precision="1" :step="1" :min="0" :max="100" />
              <span style="margin-left: 10px;">%</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="湿度最高值" prop="humidityMax">
              <el-input-number v-model="form.humidityMax" :precision="1" :step="1" :min="0" :max="100" />
              <span style="margin-left: 10px;">%</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="form.airQualityAlert == '1'">
          <el-col :span="12">
            <el-form-item label="空气质量最低值" prop="airQualityMin">
              <el-input-number v-model="form.airQualityMin" :precision="0" :step="1" :min="0" :max="500" />
              <span style="margin-left: 10px;">AQI</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="空气质量最高值" prop="airQualityMax">
              <el-input-number v-model="form.airQualityMax" :precision="0" :step="1" :min="0" :max="500" />
              <span style="margin-left: 10px;">AQI</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">通知方式</el-divider>

        <el-row>
          <el-col :span="8">
            <el-form-item label="邮件通知">
              <el-switch
                v-model="form.emailNotification"
                active-value="1"
                inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="短信通知">
              <el-switch
                v-model="form.smsNotification"
                active-value="1"
                inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="应用内通知">
              <el-switch
                v-model="form.appNotification"
                active-value="1"
                inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 我的通知设置对话框 -->
    <el-dialog title="我的通知设置" :visible.sync="mySettingsOpen" width="800px" append-to-body>
      <el-form ref="myForm" :model="myForm" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="设置名称">
              <el-input v-model="myForm.settingName" placeholder="请输入设置名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用状态">
              <el-switch
                v-model="myForm.isEnabled"
                active-value="1"
                inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">报警设置</el-divider>
        
        <el-row>
          <el-col :span="8">
            <el-form-item label="温度报警">
              <el-switch
                v-model="myForm.temperatureAlert"
                active-value="1"
                inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="湿度报警">
              <el-switch
                v-model="myForm.humidityAlert"
                active-value="1"
                inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="空气质量报警">
              <el-switch
                v-model="myForm.airQualityAlert"
                active-value="1"
                inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="气压报警">
              <el-switch
                v-model="myForm.pressureAlert"
                active-value="1"
                inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="光照报警">
              <el-switch
                v-model="myForm.lightAlert"
                active-value="1"
                inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="设备离线报警">
              <el-switch
                v-model="myForm.deviceOfflineAlert"
                active-value="1"
                inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">报警阈值设置</el-divider>

        <el-row v-if="myForm.temperatureAlert == '1'">
          <el-col :span="12">
            <el-form-item label="温度最低值">
              <el-input-number v-model="myForm.temperatureMin" :precision="1" :step="0.5" :min="-50" :max="100" />
              <span style="margin-left: 10px;">°C</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="温度最高值">
              <el-input-number v-model="myForm.temperatureMax" :precision="1" :step="0.5" :min="-50" :max="100" />
              <span style="margin-left: 10px;">°C</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="myForm.humidityAlert == '1'">
          <el-col :span="12">
            <el-form-item label="湿度最低值">
              <el-input-number v-model="myForm.humidityMin" :precision="1" :step="1" :min="0" :max="100" />
              <span style="margin-left: 10px;">%</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="湿度最高值">
              <el-input-number v-model="myForm.humidityMax" :precision="1" :step="1" :min="0" :max="100" />
              <span style="margin-left: 10px;">%</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="myForm.airQualityAlert == '1'">
          <el-col :span="12">
            <el-form-item label="空气质量最低值">
              <el-input-number v-model="myForm.airQualityMin" :precision="0" :step="1" :min="0" :max="500" />
              <span style="margin-left: 10px;">AQI</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="空气质量最高值">
              <el-input-number v-model="myForm.airQualityMax" :precision="0" :step="1" :min="0" :max="500" />
              <span style="margin-left: 10px;">AQI</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">通知方式</el-divider>

        <el-row>
          <el-col :span="8">
            <el-form-item label="邮件通知">
              <el-switch
                v-model="myForm.emailNotification"
                active-value="1"
                inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="短信通知">
              <el-switch
                v-model="myForm.smsNotification"
                active-value="1"
                inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="应用内通知">
              <el-switch
                v-model="myForm.appNotification"
                active-value="1"
                inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateMySettings">保存设置</el-button>
        <el-button @click="initMySettings">初始化设置</el-button>
        <el-button @click="mySettingsOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 检测报警对话框 -->
    <el-dialog title="检测报警条件" :visible.sync="alertCheckOpen" width="600px" append-to-body>
      <el-form ref="alertForm" :model="alertForm" label-width="120px">
        <el-form-item label="温度值" prop="temperature">
          <el-input-number v-model="alertForm.temperature" :precision="1" :step="0.5" :min="-50" :max="100" />
          <span style="margin-left: 10px;">°C</span>
        </el-form-item>
        <el-form-item label="湿度值" prop="humidity">
          <el-input-number v-model="alertForm.humidity" :precision="1" :step="1" :min="0" :max="100" />
          <span style="margin-left: 10px;">%</span>
        </el-form-item>
        <el-form-item label="空气质量值" prop="airQuality">
          <el-input-number v-model="alertForm.airQuality" :precision="0" :step="1" :min="0" :max="500" />
          <span style="margin-left: 10px;">AQI</span>
        </el-form-item>
        <el-form-item label="气压值" prop="pressure">
          <el-input-number v-model="alertForm.pressure" :precision="1" :step="0.1" :min="800" :max="1200" />
          <span style="margin-left: 10px;">hPa</span>
        </el-form-item>
        <el-form-item label="光照值" prop="light">
          <el-input-number v-model="alertForm.light" :precision="0" :step="1" :min="0" :max="100000" />
          <span style="margin-left: 10px;">lux</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="checkAlert">检测报警</el-button>
        <el-button @click="alertCheckOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listNotificationSetting, getNotificationSetting, delNotificationSetting, addNotificationSetting, updateNotificationSetting, exportNotificationSetting, getCurrentUserNotificationSetting, updateCurrentUserNotificationSetting, initNotificationSetting, checkAlertCondition } from "@/api/environment/notification";

export default {
  name: "Notification",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 通知设置表格数据
      notificationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示我的设置弹出层
      mySettingsOpen: false,
      // 是否显示报警检测弹出层
      alertCheckOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        settingName: null,
        isEnabled: null
      },
      // 表单参数
      form: {},
      // 我的设置表单参数
      myForm: {},
      // 报警检测表单参数
      alertForm: {},
      // 当前选中的设置ID
      currentSettingId: null,
      // 表单校验
      rules: {
        settingName: [
          { required: true, message: "设置名称不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询通知设置列表 */
    getList() {
      this.loading = true;
      listNotificationSetting(this.queryParams).then(response => {
        this.notificationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        settingId: null,
        userId: null,
        settingName: null,
        temperatureAlert: "0",
        humidityAlert: "0",
        airQualityAlert: "0",
        pressureAlert: "0",
        lightAlert: "0",
        deviceOfflineAlert: "0",
        temperatureMin: 18.0,
        temperatureMax: 26.0,
        humidityMin: 40.0,
        humidityMax: 70.0,
        airQualityMin: 0,
        airQualityMax: 100,
        pressureMin: 1000.0,
        pressureMax: 1020.0,
        lightMin: 100,
        lightMax: 1000,
        emailNotification: "1",
        smsNotification: "0",
        appNotification: "1",
        isEnabled: "1",
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.settingId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加通知设置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const settingId = row.settingId || this.ids
      getNotificationSetting(settingId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改通知设置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.settingId != null) {
            updateNotificationSetting(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addNotificationSetting(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const settingIds = row.settingId || this.ids;
      this.$modal.confirm('是否确认删除通知设置编号为"' + settingIds + '"的数据项？').then(function() {
        return delNotificationSetting(settingIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('environment/notification/export', {
        ...this.queryParams
      }, `notification_${new Date().getTime()}.xlsx`)
    },
    /** 我的设置按钮操作 */
    handleMySettings() {
      getMyNotificationSetting().then(response => {
        if (response.data) {
          this.myForm = response.data;
        } else {
          this.myForm = {
            settingName: "我的通知设置",
            temperatureAlert: "1",
            humidityAlert: "1",
            airQualityAlert: "1",
            pressureAlert: "0",
            lightAlert: "0",
            deviceOfflineAlert: "1",
            temperatureMin: 18.0,
            temperatureMax: 26.0,
            humidityMin: 40.0,
            humidityMax: 70.0,
            airQualityMin: 0,
            airQualityMax: 100,
            pressureMin: 1000.0,
            pressureMax: 1020.0,
            lightMin: 100,
            lightMax: 1000,
            emailNotification: "1",
            smsNotification: "0",
            appNotification: "1",
            isEnabled: "1"
          };
        }
        this.mySettingsOpen = true;
      });
    },
    /** 更新我的设置 */
    updateMySettings() {
      updateMyNotificationSetting(this.myForm).then(response => {
        this.$modal.msgSuccess("设置保存成功");
        this.mySettingsOpen = false;
      });
    },
    /** 初始化我的设置 */
    initMySettings() {
      this.$modal.confirm('是否确认初始化通知设置？这将重置为默认配置。').then(() => {
        initNotificationSetting().then(response => {
          this.$modal.msgSuccess("初始化成功");
          this.handleMySettings(); // 重新加载设置
        });
      }).catch(() => {});
    },
    /** 检测报警按钮操作 */
    handleCheckAlert(row) {
      this.currentSettingId = row.settingId;
      this.alertForm = {
        temperature: 25.0,
        humidity: 60.0,
        airQuality: 50,
        pressure: 1013.25,
        light: 500
      };
      this.alertCheckOpen = true;
    },
    /** 检测报警 */
    checkAlert() {
      const params = {
        settingId: this.currentSettingId,
        ...this.alertForm
      };
      checkAlertCondition(params).then(response => {
        if (response.data) {
          this.$modal.msgWarning("检测到报警条件！当前环境参数超出设定阈值。");
        } else {
          this.$modal.msgSuccess("环境参数正常，未触发报警条件。");
        }
        this.alertCheckOpen = false;
      });
    }
  }
};
</script>